# This file is executed on every boot (including wake-boot from deepsleep)
#import esp
#esp.osdebug(None)
import machine
import touchtool
import sys,os

touch,touchExtends,wifi,weixinWebhook,time,httpServer = touchtool.init()

ssid = None
pwd  = None

webhook_key = "137ebec8-037a-43e4-b434-943d466402fc"

# def randint(min, max):
#     span = max - min + 1
#     div = 0x3fffffff // span
    
#     offset = random.getrandbits(30) // div
#     val = min + offset
#     return val
#文件是否存在
def isExists(pth):
    try:
        f = open(pth,'rb')
        f.close()
        return True
    except Exception:
        return False
isStop = False
TIMEROBJ = None
def heartbeat(tim):
    global isStop
    try:
        touchExtends.timerActionTouchConfig()
    except Exception as e:
        sys.print_exception(e)
    if not touch.key.value():
        isStop = True
    if isStop:
        return
    tim.init(period=1000,  mode=machine.Timer.ONE_SHOT, callback=heartbeat)

def setTimer(state = True):
    global TIMEROBJ,isStop
    print('setTimer')
    if TIMEROBJ:
        if state:
            print('start timer2')
            TIMEROBJ.deinit()
            isStop = False
            time.sleep_ms(100)
            TIMEROBJ.init(period=1000,  mode=machine.Timer.ONE_SHOT, callback=heartbeat)
        else:
            isStop = True

def connectWifi():
    # 连接新的Wi-Fi
    connectST = -1
    if isExists('wifi.txt'):
        if wifi.do_connect():#连接成功
            # weixinWebhook.webhook_notify("设备已连接WIFI网络：" + wifi.getIpAddr(), webhook_key)
            connectST = 0
        else:
            connectST = 1
    elif (ssid != None) and (pwd != None):
        if wifi.do_connect(ssid,pwd):
            connectST = 0
        else: 
            connectST = 2

    if connectST == -1:
        print("no file:wifi.txt,and not wifi message from main.py,please input wifi message from serial port!")
        print('input famrat:\nssid,pwd\\n')
        while True:
            dat = touchtool.readUART()
            if dat:
                if type(dat) == bytes:
                    dat = dat.decode().strip()
                print(dat)
                tmps = dat.split(',')
                if wifi.do_connect(tmps[0],tmps[1]):
                    # weixinWebhook.webhook_notify("设备已连接WIFI网络：" + wifi.getIpAddr(), webhook_key)
                    connectST = 0
                    f = open('wifi.txt','w')
                    f.write(dat)
                    f.close()
                break
            time.sleep_ms(300)
    elif connectST != 0:
        print('net connect fail:%d',connectST)
        # weixinWebhook.webhook_notify("设备连接WIFI网络失败", webhook_key)
        machine.reset()
    else:
        print('net connect success')
        # weixinWebhook.webhook_notify("设备已连接WIFI网络：" + wifi.getIpAddr(), webhook_key)

def clearwifi():
    touchtool.writeUART('clearwifi')

#主函数,点击器程序从这里开始运行
def main():
    global TIMEROBJ
    touch.set16Pins(0b0000000000000000)
    touch.updateData()
    time.sleep(1)
    touch.set16Pins(0b1111111111111111)
    touch.updateData()
    tkey = touch.key.value()
    if not tkey:#板子启动时按键被按下状态,就清除wifi
        os.remove('wifi.txt')
        time.sleep_ms(100)
    #连接wifi
    connectWifi()

    
    # 自动同步时间
    time.syncRemote()
    # weixinWebhook.webhook_notify("设备时钟已同步：" + time.getBjTime(), webhook_key)
    
    # 心跳
    TIMEROBJ = machine.Timer(-1)
    #每秒检测一次是否有新的点击设置
    # TIMEROBJ.init(period=1000,  mode=machine.Timer.ONE_SHOT, callback=heartbeat)
    touchExtends.setTimerFunc(setTimer)
    # 启动httpServer
    httpServer.start_http_server(touchtool.HttpActions())

    print("start over!")

if __name__ == '__main__':  
    main()
    